package cn.josewu.config;


import cn.josewu.config.CustomerPartitioner.CustomerPartitioner;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: covid19
 * @description: kafka配置类
 * @author: Mr. Tigger
 * @create 2020-11-12 10:31
 **/
@Configuration
public class KafkaProducerConfig {

    @Value("${kafka.producer.servers}")
    private String servers;
    @Value("${kafka.producer.retries}")
    private String retries;
    @Value("${kafka.producer.batch.size}")
    private String batchSize;
    @Value("${kafka.producer.linger}")
    private String linger;
    @Value("${kafka.producer.buffer.memory}")
    private String bufferMemory;

    @Bean
    public KafkaTemplate getKafkaTemplate(){
        Map<String,Object> configs = new HashMap<>();

        configs.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,servers);
        configs.put(ProducerConfig.RETRIES_CONFIG,retries);
        configs.put(ProducerConfig.BATCH_SIZE_CONFIG,batchSize);
        configs.put(ProducerConfig.LINGER_MS_CONFIG,linger);
        configs.put(ProducerConfig.BUFFER_MEMORY_CONFIG,bufferMemory);

        configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
        //configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, CustomerPartitioner.class);


        DefaultKafkaProducerFactory producerFactory =  new DefaultKafkaProducerFactory(configs);
        KafkaTemplate kafkaTemplate = new KafkaTemplate(producerFactory);
        return kafkaTemplate;
    }
}
